package ru.ifmo.rybakov.muclumon.pes;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import ru.ifmo.rybakov.muclumon.Database;
import ru.ifmo.rybakov.muclumon.Task;
import ru.ifmo.rybakov.muclumon.pes.sr.SequenceRunType;
import ru.ifmo.rybakov.muclumon.pes.sri.SequenceRunInfo;

public class SequenceRunFailedEventHandler implements IEventHandler {

	private static final Logger logger = LoggerFactory.getLogger(SequenceRunFailedEventHandler.class);
	
	@SuppressWarnings("unchecked")
	@Override
	public void handle(SequenceRunInfo sequenceRunInfo,
			SequenceRunType sequenceRun) {
		
		// look for the task
		EntityManager em = Database.getEntityManagerFactory().createEntityManager();
		try {
			Query query = em.createQuery("SELECT t FROM Task t WHERE t.foreignId = :id");
			query.setParameter("id", Integer.valueOf(sequenceRun.getId().intValue()));
			List<Task> tasks = query.getResultList();
			if (tasks == null || tasks.size() != 1) {
				logger.warn("No task found, skipping event");
				return;
			}
			Task task = tasks.get(0);
			
			EntityTransaction t = em.getTransaction();
			try {
				t.begin();
				em.remove(task); // remove task from database
				logger.warn("Task run failed, task {} removed from database", task.getId());
				t.commit();
			} finally {
				if (t.isActive()) t.rollback();
			}
		} finally {
			em.close();
		}
		
		logger.debug("Sequence run failed, task information updated");
//		TaskObserver.getInstance().notifyOnTaskStopped();
	}

}
